<template>
  <div class="rbo-rule-engine">
    <div class="rule-engine-header">
      <h3>RBO规则引擎</h3>
      <div class="header-actions">
        <Button @click="addRule" type="primary">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加规则
        </Button>
        <Button @click="saveRules" type="default">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存规则
        </Button>
      </div>
    </div>

    <div class="rule-engine-content">
      <!-- 左侧规则列表 -->
      <div class="rules-panel">
        <div class="rules-header">
          <h4>规则列表</h4>
          <Input
            v-model="searchKeyword"
            placeholder="搜索规则"
            size="small"
            style="width: 200px"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:search-outlined" />
            </template>
          </Input>
        </div>

        <div class="rules-list">
          <div
            v-for="rule in filteredRules"
            :key="rule.id"
            class="rule-item"
            :class="{ 'rule-selected': selectedRule?.id === rule.id }"
            @click="selectRule(rule)"
          >
            <div class="rule-header">
              <div class="rule-name">{{ rule.name }}</div>
              <div class="rule-status">
                <Tag :color="rule.enabled ? 'green' : 'red'">
                  {{ rule.enabled ? '启用' : '禁用' }}
                </Tag>
              </div>
            </div>
            <div class="rule-description">{{ rule.description }}</div>
            <div class="rule-meta">
              <span>优先级: {{ rule.priority }}</span>
              <span>类型: {{ getRuleTypeLabel(rule.type) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧规则编辑器 -->
      <div class="rule-editor">
        <div v-if="selectedRule" class="editor-content">
          <div class="editor-header">
            <h4>编辑规则: {{ selectedRule.name }}</h4>
            <div class="editor-actions">
              <Button @click="testRule" type="default" size="small">
                <IconifyIcon icon="ant-design:play-circle-outlined" />
                测试规则
              </Button>
              <Button @click="deleteRule" type="default" size="small" danger>
                <IconifyIcon icon="ant-design:delete-outlined" />
                删除规则
              </Button>
            </div>
          </div>

          <Form layout="vertical" :model="selectedRule">
            <FormItem label="规则名称">
              <Input v-model="selectedRule.name" />
            </FormItem>

            <FormItem label="规则描述">
              <Textarea v-model="selectedRule.description" :rows="2" />
            </FormItem>

            <Row :gutter="16">
              <Col :span="8">
                <FormItem label="规则类型">
                  <Select v-model="selectedRule.type">
                    <SelectOption value="condition">条件规则</SelectOption>
                    <SelectOption value="action">动作规则</SelectOption>
                    <SelectOption value="validation">验证规则</SelectOption>
                    <SelectOption value="calculation">计算规则</SelectOption>
                  </Select>
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="优先级">
                  <InputNumber
                    v-model="selectedRule.priority"
                    :min="1"
                    :max="100"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="状态">
                  <Switch v-model="selectedRule.enabled" />
                </FormItem>
              </Col>
            </Row>

            <!-- 条件配置 -->
            <div class="condition-section">
              <h5>条件配置</h5>
              <div class="condition-builder">
                <div
                  v-for="(condition, index) in selectedRule.conditions"
                  :key="index"
                  class="condition-item"
                >
                  <Row :gutter="16">
                    <Col :span="6">
                      <Select v-model="condition.field" placeholder="选择字段">
                        <SelectOption
                          v-for="field in availableFields"
                          :key="field.name"
                          :value="field.name"
                        >
                          {{ field.label }}
                        </SelectOption>
                      </Select>
                    </Col>
                    <Col :span="4">
                      <Select v-model="condition.operator" placeholder="操作符">
                        <SelectOption value="eq">等于</SelectOption>
                        <SelectOption value="ne">不等于</SelectOption>
                        <SelectOption value="gt">大于</SelectOption>
                        <SelectOption value="gte">大于等于</SelectOption>
                        <SelectOption value="lt">小于</SelectOption>
                        <SelectOption value="lte">小于等于</SelectOption>
                        <SelectOption value="in">包含</SelectOption>
                        <SelectOption value="not_in">不包含</SelectOption>
                      </Select>
                    </Col>
                    <Col :span="8">
                      <Input v-model="condition.value" placeholder="值" />
                    </Col>
                    <Col :span="4">
                      <Select v-model="condition.logic" placeholder="逻辑">
                        <SelectOption value="and">AND</SelectOption>
                        <SelectOption value="or">OR</SelectOption>
                      </Select>
                    </Col>
                    <Col :span="2">
                      <Button
                        type="text"
                        size="small"
                        danger
                        @click="removeCondition(index)"
                      >
                        <IconifyIcon icon="ant-design:delete-outlined" />
                      </Button>
                    </Col>
                  </Row>
                </div>
                <Button @click="addCondition" type="dashed" block>
                  <IconifyIcon icon="ant-design:plus-outlined" />
                  添加条件
                </Button>
              </div>
            </div>

            <!-- 动作配置 -->
            <div class="action-section">
              <h5>动作配置</h5>
              <div class="action-builder">
                <div
                  v-for="(action, index) in selectedRule.actions"
                  :key="index"
                  class="action-item"
                >
                  <Row :gutter="16">
                    <Col :span="6">
                      <Select v-model="action.type" placeholder="动作类型">
                        <SelectOption value="set_field">设置字段</SelectOption>
                        <SelectOption value="call_service"
                          >调用服务</SelectOption
                        >
                        <SelectOption value="send_event">发送事件</SelectOption>
                        <SelectOption value="execute_behavior"
                          >执行行为</SelectOption
                        >
                      </Select>
                    </Col>
                    <Col :span="8">
                      <Input v-model="action.target" placeholder="目标" />
                    </Col>
                    <Col :span="6">
                      <Input v-model="action.value" placeholder="值" />
                    </Col>
                    <Col :span="4">
                      <Button
                        type="text"
                        size="small"
                        danger
                        @click="removeAction(index)"
                      >
                        <IconifyIcon icon="ant-design:delete-outlined" />
                      </Button>
                    </Col>
                  </Row>
                </div>
                <Button @click="addAction" type="dashed" block>
                  <IconifyIcon icon="ant-design:plus-outlined" />
                  添加动作
                </Button>
              </div>
            </div>

            <!-- 高级配置 -->
            <div class="advanced-section">
              <h5>高级配置</h5>
              <Row :gutter="16">
                <Col :span="12">
                  <FormItem label="执行超时(秒)">
                    <InputNumber
                      v-model="selectedRule.timeout"
                      :min="1"
                      :max="3600"
                    />
                  </FormItem>
                </Col>
                <Col :span="12">
                  <FormItem label="重试次数">
                    <InputNumber
                      v-model="selectedRule.retry"
                      :min="0"
                      :max="10"
                    />
                  </FormItem>
                </Col>
              </Row>
              <FormItem label="错误处理">
                <Select
                  v-model="selectedRule.errorHandling"
                  placeholder="选择错误处理方式"
                >
                  <SelectOption value="continue">继续执行</SelectOption>
                  <SelectOption value="stop">停止执行</SelectOption>
                  <SelectOption value="rollback">回滚</SelectOption>
                </Select>
              </FormItem>
            </div>
          </Form>
        </div>
        <div v-else class="no-selection">
          <p>请选择一个规则进行编辑</p>
        </div>
      </div>
    </div>

    <!-- 规则测试模态框 -->
    <Modal
      v-model:open="testModalVisible"
      title="规则测试"
      width="800px"
      :footer="null"
    >
      <div class="rule-test-content">
        <Form layout="vertical">
          <FormItem label="测试数据">
            <Textarea
              v-model="testData"
              :rows="8"
              placeholder="输入JSON格式的测试数据"
            />
          </FormItem>
          <Button @click="executeTest" type="primary">执行测试</Button>
        </Form>

        <div v-if="testResult" class="test-result">
          <h5>测试结果</h5>
          <pre>{{ JSON.stringify(testResult, null, 2) }}</pre>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import {
  Button,
  Input,
  InputNumber,
  Form,
  FormItem,
  Textarea,
  Select,
  SelectOption,
  Switch,
  Tag,
  Row,
  Col,
  Modal,
  message,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// 规则接口定义
interface Rule {
  id: string;
  name: string;
  description: string;
  type: 'condition' | 'action' | 'validation' | 'calculation';
  priority: number;
  enabled: boolean;
  conditions: Array<{
    field: string;
    operator: string;
    value: string;
    logic: 'and' | 'or';
  }>;
  actions: Array<{
    type: string;
    target: string;
    value: string;
  }>;
  timeout: number;
  retry: number;
  errorHandling: 'continue' | 'stop' | 'rollback';
}

// 可用字段定义
const availableFields = [
  { name: 'resource.state', label: '资源状态' },
  { name: 'resource.type', label: '资源类型' },
  { name: 'user.role', label: '用户角色' },
  { name: 'user.permissions', label: '用户权限' },
  { name: 'context.tenant', label: '租户' },
  { name: 'context.environment', label: '环境' },
];

// 响应式数据
const rules = ref<Rule[]>([]);
const selectedRule = ref<Rule | null>(null);
const searchKeyword = ref('');
const testModalVisible = ref(false);
const testData = ref('');
const testResult = ref<any>(null);

// 计算属性
const filteredRules = computed(() => {
  if (!searchKeyword.value) return rules.value;
  return rules.value.filter(
    (rule) =>
      rule.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      rule.description
        .toLowerCase()
        .includes(searchKeyword.value.toLowerCase()),
  );
});

// 方法
const getRuleTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    condition: '条件规则',
    action: '动作规则',
    validation: '验证规则',
    calculation: '计算规则',
  };
  return labels[type] || type;
};

const addRule = () => {
  const newRule: Rule = {
    id: `rule_${Date.now()}`,
    name: '新规则',
    description: '',
    type: 'condition',
    priority: 50,
    enabled: true,
    conditions: [],
    actions: [],
    timeout: 60,
    retry: 1,
    errorHandling: 'continue',
  };

  rules.value.push(newRule);
  selectRule(newRule);
};

const selectRule = (rule: Rule) => {
  selectedRule.value = { ...rule };
};

const saveRules = () => {
  // 这里可以调用API保存规则
  console.log('保存规则:', rules.value);
  message.success('规则保存成功');
};

const deleteRule = () => {
  if (!selectedRule.value) return;

  rules.value = rules.value.filter(
    (rule) => rule.id !== selectedRule.value!.id,
  );
  selectedRule.value = null;
  message.success('规则删除成功');
};

const addCondition = () => {
  if (!selectedRule.value) return;

  selectedRule.value.conditions.push({
    field: '',
    operator: 'eq',
    value: '',
    logic: 'and',
  });
};

const removeCondition = (index: number) => {
  if (!selectedRule.value) return;

  selectedRule.value.conditions.splice(index, 1);
};

const addAction = () => {
  if (!selectedRule.value) return;

  selectedRule.value.actions.push({
    type: 'set_field',
    target: '',
    value: '',
  });
};

const removeAction = (index: number) => {
  if (!selectedRule.value) return;

  selectedRule.value.actions.splice(index, 1);
};

const testRule = () => {
  if (!selectedRule.value) return;

  testModalVisible.value = true;
  testData.value = JSON.stringify(
    {
      resource: { state: 'idle', type: 'room' },
      user: { role: 'admin', permissions: ['read', 'write'] },
      context: { tenant: 'default', environment: 'production' },
    },
    null,
    2,
  );
};

const executeTest = () => {
  try {
    const data = JSON.parse(testData.value);

    // 模拟规则执行
    const result = {
      matched: true,
      conditions: selectedRule.value?.conditions.map((condition) => ({
        ...condition,
        result: Math.random() > 0.5,
      })),
      actions: selectedRule.value?.actions.map((action) => ({
        ...action,
        executed: true,
        result: 'success',
      })),
      executionTime: Math.random() * 100,
    };

    testResult.value = result;
    message.success('规则测试执行成功');
  } catch (error) {
    message.error('测试数据格式错误');
  }
};

// 初始化示例数据
const initSampleRules = () => {
  rules.value = [
    {
      id: 'rule_1',
      name: '房间预订规则',
      description: '检查房间状态和用户权限',
      type: 'condition',
      priority: 80,
      enabled: true,
      conditions: [
        {
          field: 'resource.state',
          operator: 'eq',
          value: 'idle',
          logic: 'and',
        },
        {
          field: 'user.permissions',
          operator: 'in',
          value: 'reserve',
          logic: 'and',
        },
      ],
      actions: [
        {
          type: 'set_field',
          target: 'resource.state',
          value: 'reserved',
        },
      ],
      timeout: 30,
      retry: 1,
      errorHandling: 'stop',
    },
  ];
};

// 初始化
initSampleRules();
</script>

<style lang="less" scoped>
.rbo-rule-engine {
  height: 100%;
  display: flex;
  flex-direction: column;

  .rule-engine-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .rule-engine-content {
    flex: 1;
    display: flex;
    overflow: hidden;

    .rules-panel {
      width: 350px;
      border-right: 1px solid #f0f0f0;
      display: flex;
      flex-direction: column;

      .rules-header {
        padding: 16px;
        border-bottom: 1px solid #f0f0f0;

        h4 {
          margin-bottom: 12px;
        }
      }

      .rules-list {
        flex: 1;
        overflow-y: auto;
        padding: 8px;

        .rule-item {
          padding: 12px;
          border: 1px solid #f0f0f0;
          border-radius: 6px;
          margin-bottom: 8px;
          cursor: pointer;
          transition: all 0.2s;

          &:hover {
            border-color: #1890ff;
            background: #f0f8ff;
          }

          &.rule-selected {
            border-color: #1890ff;
            background: #e6f7ff;
          }

          .rule-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;

            .rule-name {
              font-weight: 500;
            }
          }

          .rule-description {
            color: #666;
            font-size: 12px;
            margin-bottom: 8px;
          }

          .rule-meta {
            display: flex;
            gap: 12px;
            font-size: 11px;
            color: #999;
          }
        }
      }
    }

    .rule-editor {
      flex: 1;
      padding: 16px;
      overflow-y: auto;

      .editor-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;

        h4 {
          margin: 0;
        }

        .editor-actions {
          display: flex;
          gap: 8px;
        }
      }

      .no-selection {
        text-align: center;
        color: #666;
        padding: 40px 20px;
      }

      .condition-section,
      .action-section,
      .advanced-section {
        margin-top: 24px;

        h5 {
          margin-bottom: 16px;
          color: #333;
        }

        .condition-item,
        .action-item {
          margin-bottom: 12px;
          padding: 12px;
          border: 1px solid #f0f0f0;
          border-radius: 4px;
          background: #fafafa;
        }
      }
    }
  }

  .rule-test-content {
    .test-result {
      margin-top: 24px;

      h5 {
        margin-bottom: 12px;
      }

      pre {
        background: #f5f5f5;
        padding: 12px;
        border-radius: 4px;
        overflow-x: auto;
        font-size: 12px;
      }
    }
  }
}
</style>
